<?php

namespace App\Http\Services;

use App\Http\Dao\MemoDao;
use App\Http\Dao\RemindDao;
use App\Models\RemindModel;
use Illuminate\Support\Facades\DB;

/**
 * @property RemindDao $remindDao
 */
class RemindService
{


    public function __construct(RemindDao $remindDao)
    {
        $this->remindDao = $remindDao;
    }

    public function getList($post)
    {
        $query = RemindModel::query()->where('user_id', request()->userInfo['id']);
        $query->with('memos', function ($query) use ($post) {
            $query->where('status', 0);
            if (!empty($post['search_values']) && $post['search_values'] != 'undefined') {
                $query->where(function ($query) use ($post) {
                    $query->where('title', 'like', '%' . $post['search_values'] . '%')
                        ->orWhere('desc', 'like', '%' . $post['search_values'] . '%');
                });
            }
        });
        $list = $query->orderBy($post['sort'], $post['by'])->paginate($post['page_size'])->toArray();
        if(!empty($list['data'])){
            foreach ($list['data'] as $key => $item){
                if(!empty($item['memos'])){
                    continue;
                }
                unset($list['data'][$key]);
            }
        }
        return $list;
    }

    public function addRemind($post)
    {
        try {
            Db::transaction(function () use ($post) {
                $memosInfo = (new MemoDao())->getOne(['id' => $post['memos_id']]);
                $memosInfo->reminder_time = $post['remind_time'];
                if(!$memosInfo->save()){
                    throw new \Exception('保存失败');
                }

                $addRemind = [
                    'memos_id' => $post['memos_id'],
                    'user_id' => request()->userInfo['id'],
                    'sent_time' => $post['remind_time'],
                ];
                $result =  $this->remindDao->add($addRemind);
                if (!$result) {
                    throw new \Exception('添加失败');
                }
            });
            return true;
        }catch (\Exception $e) {
            return false;
        }
    }

    public function deleteRemind($id)
    {
        return $this->remindDao->deleteOne($id);
    }
}
